package com.jctrip.hotel.source.xxl.hmein;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jctrip.hotel.common.constant.XxlJobNameConstant;
import com.jctrip.hotel.common.util.JsonUtil;
import com.jctrip.hotel.domain.dao.HtSourceInfoDao;
import com.jctrip.hotel.domain.entity.HtSourceInfo;
import com.jctrip.hotel.source.model.CommonJobParam;
import com.jctrip.hotel.source.service.hmein.HmeinTaskService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zxy
 * @CreateTime: 2023-08-15 16:12
 * @Description:
 */
@Component
@Slf4j
public class SyncHmeinHotspotRatesTaskPopXxlJob extends IJobHandler {
    @Resource
    private HmeinTaskService hmeinTaskService;
    @Resource
    private HtSourceInfoDao htSourceInfoDao;

    @Override
    @XxlJob(XxlJobNameConstant.SYNC_HMEIN_HOTSPOT_RATES_TASK_POP)
    public void execute() throws Exception {
        XxlJobHelper.log(XxlJobNameConstant.SYNC_HMEIN_HOTSPOT_RATES_TASK_POP + " xxl job start");

        try {
            CommonJobParam commonJobParam = JsonUtil.toObject(CommonJobParam.class, XxlJobHelper.getJobParam());
            List<HtSourceInfo> htSourceInfos = htSourceInfoDao.selectList(new LambdaQueryWrapper<HtSourceInfo>()
                    .in(HtSourceInfo::getSourceId, commonJobParam.getSourceIds()));

            if (CollectionUtils.isEmpty(htSourceInfos)) {
                return;
            }
            // todo 目前是多source拉取 ，但是 appId 和 memberNo 使用相同，除了rateCode 不同
            String sourceAppId = htSourceInfos.get(0).getSourceAppId();
            String memberNo = (String) JsonUtil.toMap(htSourceInfos.get(0).getExtra()).get("memberNo");
            String trustMemberNo = (String) JsonUtil.toMap(htSourceInfos.get(0).getExtra()).get("trustMemberNo");
            // 价格码 ： 供应拉取id
            Map<String, String> rateCodeWithSourceIdMap = htSourceInfos.stream()
                    .collect(Collectors.toMap(e -> (String) JsonUtil.toMap(e.getExtra()).get("rateCode"), HtSourceInfo::getSourceId));

            hmeinTaskService.syncHmeinHotspotRatesTaskFastPop(sourceAppId,
                    StringUtils.isBlank(trustMemberNo) ? memberNo : trustMemberNo, commonJobParam.getDays(),
                    rateCodeWithSourceIdMap);
        } catch (Exception e) {
            log.error(XxlJobNameConstant.SYNC_HMEIN_HOTSPOT_RATES_TASK_POP + "error", e);
        }

        XxlJobHelper.log(XxlJobNameConstant.SYNC_HMEIN_HOTSPOT_RATES_TASK_POP + " xxl job end");
    }
}